package com.cuiweiyou.arduinogirl.ui;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.le.ScanResult;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.cuiweiyou.arduinogirl.base.ExitAppActivity;
import com.cuiweiyou.arduinogirl.bluetooth.BluetoothMaster;
import com.cuiweiyou.arduinogirl.model.EventArduinoModel;
import com.cuiweiyou.arduinogirl.model.EventDeviceModel;
import com.cuiweiyou.arduinogirl.model.EventGattedModel;
import com.cuiweiyou.catwristhands.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends ExitAppActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.chatEditText)
    EditText chatEditText;

    @BindView(R.id.msgEditText)
    EditText msgEditText;

    DevicesAdapter devicesAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initView();
        BluetoothMaster.getInstance().scan();
    }

    @Override
    public void whenAppExit() {
        EventBus.getDefault().unregister(this);
        BluetoothMaster.getInstance().release();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onDeviceEvent(EventDeviceModel model) { // 设备列表刷新
        List<ScanResult> deviceResultList = BluetoothMaster.getInstance().getDevices();
        if (null != devicesAdapter) {
            devicesAdapter.updateDevices(deviceResultList);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGattEvent(EventGattedModel model) {
        Log.e("ard", "收到设备状态变更信息(1连接，0断开)：" + model.getFlag());
        if (null != devicesAdapter) {
            if (1 == model.getFlag()) { // 连接了
                ScanResult selected = BluetoothMaster.getInstance().getGattDevice();
                BluetoothMaster.getInstance().getGattDeviceServices();
                devicesAdapter.setSelected(selected);
            } else { // 断开了
                devicesAdapter.setSelected(null);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onArduinoEvent(EventArduinoModel model) {
        String msg = model.getMsg();
        chatEditText.append("Arduino发来：" + msg + "\n");
        Log.e("ard", "收到Arduino信息：" + msg);
    }

    @OnClick(R.id.sendTextView)
    public void onSendViewClicked() {
        if (null != BluetoothMaster.getInstance().getGattDevice()) {
            String msg = msgEditText.getText().toString().trim();
            BluetoothMaster.getInstance().sendMsgToBlueTooth(onCharacteristicWritedListener, msg);
        } else {
            Toast.makeText(this, "请连接设备", Toast.LENGTH_SHORT).show();
        }
    }

    private void initView() {
        devicesAdapter = new DevicesAdapter(null);
        devicesAdapter.setOnDeviceClickListener(onDeviceClickListener);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(devicesAdapter);
    }

    DevicesAdapter.OnDeviceClickListener onDeviceClickListener = new DevicesAdapter.OnDeviceClickListener() {
        @Override
        public void onDeviceClick(ScanResult model) {
            BluetoothMaster.getInstance().connectDevice(model);
        }
    };

    private BluetoothMaster.OnCharacteristicWritedListener onCharacteristicWritedListener = new BluetoothMaster.OnCharacteristicWritedListener() {
        @Override
        public void onCharacteristicWrited(BluetoothGattCharacteristic characteristic, int status, final String msg) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    chatEditText.append("Android发出：" + msg + "\n");
                    msgEditText.setText("");
                }
            });

            Log.e("ard", "发送完毕，status：" + String.format("%4s", status));
        }
    };
}
